import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi } from '../api/auth'

interface UserInfo {
  id: string
  username: string
  email: string
  avatar?: string
  createdAt: string
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'))
  const userInfo = ref<UserInfo | null>(null)

  const isAuthenticated = computed(() => !!token.value)

  const login = async (username: string, password: string) => {
    // 简化登录：允许任意用户名密码登录，不需要真实验证
    try {
      // 尝试调用 API，如果失败则使用模拟登录
      try {
        const response = await authApi.login(username, password)
        token.value = response.token
        userInfo.value = response.user
        localStorage.setItem('token', response.token)
        return response
      } catch (apiError) {
        // API 失败时，使用模拟登录
        const mockToken = `mock_token_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        const mockUser: UserInfo = {
          id: `user_${Date.now()}`,
          username: username || 'guest',
          email: `${username || 'guest'}@example.com`,
          createdAt: new Date().toISOString()
        }
        token.value = mockToken
        userInfo.value = mockUser
        localStorage.setItem('token', mockToken)
        return {
          token: mockToken,
          user: mockUser
        }
      }
    } catch (error) {
      throw error
    }
  }

  const register = async (username: string, email: string, password: string) => {
    try {
      const response = await authApi.register(username, email, password)
      token.value = response.token
      userInfo.value = response.user
      localStorage.setItem('token', response.token)
      return response
    } catch (error) {
      throw error
    }
  }

  const getUserProfile = async () => {
    if (!token.value) return
    
    try {
      const user = await authApi.getProfile()
      userInfo.value = user
      return user
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
    }
  }

  const logout = () => {
    token.value = null
    userInfo.value = null
    localStorage.removeItem('token')
  }

  return {
    token,
    userInfo,
    isAuthenticated,
    login,
    register,
    getUserProfile,
    logout
  }
})

